package pl.skubicha.service;

import java.util.List;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pl.skubicha.domain.PartialGrades;
import pl.skubicha.exceptions.GradeNotFoundException;
import pl.skubicha.repository.PartialGradesRepository;
import pl.skubicha.response.GradesDTO;
import pl.skubicha.utils.PartialGradesMapper;

@Service
public class PartialGradesRepositoryService implements GradesService< PartialGrades > {

	private static Logger logger = Logger.getLogger( PartialGradesRepositoryService.class );

	@Autowired
	private PartialGradesRepository gradesRepository;

	@Override
	public List< PartialGrades > findAllGradesForSubjectInGroup( Integer idSubject, Integer idGroup ) {
		return gradesRepository.findAllGradesForSubjectInGroup( idSubject, idGroup );
	}

	@Override
	public List< PartialGrades > findAllForUser( Integer id, Integer idSubject ) {
		return gradesRepository.findAllGradesForUser( id, idSubject );
	}

	@Override
	public PartialGrades findById( Integer id ) {
		return gradesRepository.findOne( id );
	}

	@Transactional
	@Override
	public PartialGrades create( final GradesDTO toCreate ) {
		final PartialGrades grade = PartialGradesMapper.map( toCreate );
		return gradesRepository.save( grade );
	}

	@Override
	public PartialGrades update( GradesDTO updated ) throws GradeNotFoundException {
		final PartialGrades grade = gradesRepository.findOne( updated.getId() );

		if ( grade == null ) {
			logger.debug( "Nie znaleziono oceny o id: " + updated.getId() );
			throw new GradeNotFoundException( "Nie znaleziono oceny o id: " + updated.getId() );
		}
		
		PartialGrades partialGrades = PartialGradesMapper.map( updated );

		grade.update( updated.getGrade(), updated.getSubjects(), updated.getUsers(), partialGrades.getDate(), updated.getComment() );

		return grade;
	}

	@Transactional( rollbackFor = { GradeNotFoundException.class } )
	@Override
	public PartialGrades delete( final Integer id ) throws GradeNotFoundException {

		logger.debug( " Usuwam ocenę o id: " + id );

		final PartialGrades deleted = gradesRepository.findOne( id );

		if ( deleted == null ) {
			logger.debug( "Nie znaleziono oceny o id: " + id );
			throw new GradeNotFoundException( "Nie znaleziono oceny o id: " + id );
		}

		gradesRepository.delete( deleted );
		return deleted;
	}
}
